package com.iqik.ioc.proxy;

import com.iqik.ioc.anno.Autowired;
import com.iqik.ioc.anno.Service;
import com.iqik.ioc.utils.TransactionalManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Service()
public class ProxyFactory {

    @Autowired
    private TransactionalManager transactionalManager;

    public Object getProxy(Object obj) throws Exception {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = null;
                try {
                    System.out.println("业务逻辑之前....");
                    transactionalManager.begin();
                    result = method.invoke(obj, args);
                    System.out.println("业务逻辑之后....");
                    transactionalManager.commit();
                } catch (InvocationTargetException ex) {
                    ex.printStackTrace();
                    return null;
                } catch (Exception e) {
                    System.out.println("业务逻辑异常");
//                    e.printStackTrace();
                    transactionalManager.rollback();
                    throw e;
                }
                return result;
            }
        });
    }

}
